package com.tjy.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * ClassName:HttpUtils
 * Description:http工具类
 * author: jiuyang
 * DateTime: 2024/8/13 下午4:41
 */
public class HttpUtils {

    /**
    * @description: 获取下载文件的大小
    * @date 2024/8/14 下午4:40
    */
    public static long getHttpFileContentLength(String url) throws IOException {
        int contentLength;
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = getHttpURLConnection(url);
            contentLength = httpURLConnection.getContentLength();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return contentLength;
    }

    /**
     * @description: 切分文件下载
     * @date 2024/8/14 下午4:14
     */
    public static HttpURLConnection getHttpURLConnection(String url, long startPos, long endPos) throws IOException {

        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载的区间是：{}->{}",startPos,endPos);
        if (endPos != 0) {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-" + endPos);
        } else {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-");
        }
        return httpURLConnection;
    }


    /**
     * @description: 获取HttpURLConnection连接对象
     * @date 2024/8/13 下午4:47
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws  IOException {
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        // 向文件所在服务器发送标识信息
        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1");
        return httpURLConnection;
    }

    /**
     * @description: 获取文件下载名称
     * @date 2024/8/13 下午4:47
     */
    public static String getFileName(String url) {

        int i = url.lastIndexOf("/");
        return url.substring(i + 1);

    }
}
